package com.example.weixinapireptile.common.utils;

import com.example.weixinapireptile.common.okhttp.MyOkHttpClient;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zsq
 * @version 1.0
 * @date 2021/3/31 11:06
 */
@Slf4j
public class HttpUtils {

    /**okhttp 实例**/
    private static final OkHttpClient client = MyOkHttpClient.client;

    /**解析键值对正则**/
    public static final Pattern PAT_KEY_VALUE = Pattern.compile("[\\w]*=[\\w,/]*");


    /**
     * get请求
     * @param url
     * @param params
     * @return
     */
    public static String doGet(String url, Map<String, String> params) {
        Request.Builder reqBuild = new Request.Builder();
        HttpUrl.Builder urlBuilder = HttpUrl.parse(url)
                .newBuilder();
        if (params != null) {
            params.forEach(urlBuilder::addQueryParameter);
        }

        reqBuild.url(urlBuilder.build());
        Request request = reqBuild.build();

        try (Response response = client.newCall(request).execute()){
            if (!response.isSuccessful()) {
                throw new RuntimeException("请求不成功" + response.toString());
            }
            return response.body().string();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * post表单提交
     * @return
     */
    public static String doPost(String url, Map<String, String> params) {
        FormBody.Builder formBuilder = new FormBody.Builder();
        if (params != null) {
            params.forEach(formBuilder::addEncoded);
        }

        Request request = new Request.Builder()
                .url(url)
                .post(formBuilder.build())
                .build();

        try (Response response = client.newCall(request).execute()){

            if (!response.isSuccessful()) {
                throw new RuntimeException("请求不成功" + response.toString());
            }
            return response.body().string();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * get请求，返回流
     * @param url
     * @param params
     * @return
     */
    public static InputStream doGetStream(String url, Map<String, String> params) {
        HttpUrl.Builder urlBuilder = HttpUrl.parse(url)
                .newBuilder();
        if (params != null) {
            params.forEach(urlBuilder::addQueryParameter);
        }
        // 创建请求构建器
        Request.Builder requestBuilder = new Request.Builder().url(urlBuilder.build());

        // 添加所有请求头
        Headers headers = new Headers.Builder()
//                .add("accept", "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8")
//                .add("accept-language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6")
//                .add("cookie", "ptcz=bc153e1b2697121722601ceaae31ad63c4d7e663c5673d2dc2c4b7741b08ff1a; pgv_pvid=3382729904; mm_lang=zh_CN; iip=0; qq_domain_video_guid_verify=b37dda803f3a3239; _qimei_uuid42=17c130c1d33100097b439e9907cbdd0baa2b2d3aa4; RK=7eVRrN4cvK; _qimei_h38=fdedb6b0f89e8039697a31ab02000004417b17; ua_id=IqfaV664kEMSbQBTAAAAAH_KNpUiQse3cNco0EBUmUY=; wxuin=09618486962279; tvfe_boss_uuid=aeb2605af59075c5; _qimei_fingerprint=3f1db47322ea6301eaa4c398d4c1c75e; _uetvid=da53c7c0378f11ef9fa389366f9fb4ce; eas_sid=d187V1X9H8P2v7h6Z4d5L4W601; _qimei_q32=75162953006c8ac817f76430816b87ad; _qimei_q36=2612530ecb2f81acd703e855300016b17b0f; pac_uid=0_nXshf40NDf56N; suid=user_0_nXshf40NDf56N; rewardsn=; wxtokenkey=777; _clck=3575856477%7C2%7Cfo0%7C0%7C1676|1|frl|0; noticeLoginFlag=1; openid2ticket_oDRmK5GkkNWe3dvJlDyDaKn1xSxc=2uWpYcVsM5HnxKlxD4EB8LxX87COk6Yel1a+c+nOAE4=; sig=h0189053996feaa79ae4de4b36a81260336195bb8e798eafdce4c6b27f6e8b8cea05d217480f3394d25; xid=c509f5b6628bacbfd5527db8f9c11524; cert=CStM4NPQ3CLW8p4Z2XST1AsxXKGtalII; _clsk=hx40dx|1733811156977|2|1|mp.weixin.qq.com/weheat-agent/payload/record; uuid=f9aec98afeb3f3d06e31b5c3ac2d0324")
//                .add("priority", "i")
//                .add("referer", "https://mp.weixin.qq.com/")
//                .add("sec-ch-ua", "\"Not)A;Brand\";v=\"99\", \"Microsoft Edge\";v=\"127\", \"Chromium\";v=\"127\"")
//                .add("sec-ch-ua-mobile", "?0")
//                .add("sec-ch-ua-platform", "\"Windows\"")
//                .add("sec-fetch-dest", "image")
//                .add("sec-fetch-mode", "no-cors")
//                .add("sec-fetch-site", "same-origin")
//                .add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0")
                .build();

        requestBuilder.headers(headers);

        Request request = requestBuilder.build();
        try (Response response = client.newCall(request).execute()){
            if (!response.isSuccessful()) {
                throw new RuntimeException("请求不成功" + response.toString());
            }

            if (response.body() == null) {
                throw new RuntimeException("返回内容body为空");
            }
            // 获取响应体的字节数组
            byte[] responseBodyBytes = response.body().bytes();

            // 将字节数组转换为 InputStream
            InputStream inputStream = new ByteArrayInputStream(responseBodyBytes);
            return inputStream;
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public static void main(String[] args) throws IOException {
        OkHttpClient client = new OkHttpClient();

        // 构建请求URL
        String url = "https://mp.weixin.qq.com/cgi-bin/scanloginqrcode?action=getqrcode&random=1733811194369";

        // 创建请求构建器
        Request.Builder requestBuilder = new Request.Builder().url(url);

        // 添加所有请求头
        Headers headers = new Headers.Builder()
                .add("accept", "image/jepg,image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8")
                .add("accept-language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6")
                .add("cookie", "ptcz=bc153e1b2697121722601ceaae31ad63c4d7e663c5673d2dc2c4b7741b08ff1a; pgv_pvid=3382729904; mm_lang=zh_CN; iip=0; qq_domain_video_guid_verify=b37dda803f3a3239; _qimei_uuid42=17c130c1d33100097b439e9907cbdd0baa2b2d3aa4; RK=7eVRrN4cvK; _qimei_h38=fdedb6b0f89e8039697a31ab02000004417b17; ua_id=IqfaV664kEMSbQBTAAAAAH_KNpUiQse3cNco0EBUmUY=; wxuin=09618486962279; tvfe_boss_uuid=aeb2605af59075c5; _qimei_fingerprint=3f1db47322ea6301eaa4c398d4c1c75e; _uetvid=da53c7c0378f11ef9fa389366f9fb4ce; eas_sid=d187V1X9H8P2v7h6Z4d5L4W601; _qimei_q32=75162953006c8ac817f76430816b87ad; _qimei_q36=2612530ecb2f81acd703e855300016b17b0f; pac_uid=0_nXshf40NDf56N; suid=user_0_nXshf40NDf56N; rewardsn=; wxtokenkey=777; _clck=3575856477%7C2%7Cfo0%7C0%7C1676|1|frl|0; noticeLoginFlag=1; openid2ticket_oDRmK5GkkNWe3dvJlDyDaKn1xSxc=2uWpYcVsM5HnxKlxD4EB8LxX87COk6Yel1a+c+nOAE4=; sig=h0189053996feaa79ae4de4b36a81260336195bb8e798eafdce4c6b27f6e8b8cea05d217480f3394d25; xid=c509f5b6628bacbfd5527db8f9c11524; cert=CStM4NPQ3CLW8p4Z2XST1AsxXKGtalII; _clsk=hx40dx|1733811156977|2|1|mp.weixin.qq.com/weheat-agent/payload/record; uuid=f9aec98afeb3f3d06e31b5c3ac2d0324")
                .add("priority", "i")
                .add("referer", "https://mp.weixin.qq.com/")
                .add("sec-ch-ua", "\"Not)A;Brand\";v=\"99\", \"Microsoft Edge\";v=\"127\", \"Chromium\";v=\"127\"")
                .add("sec-ch-ua-mobile", "?0")
                .add("sec-ch-ua-platform", "\"Windows\"")
                .add("sec-fetch-dest", "image")
                .add("sec-fetch-mode", "no-cors")
                .add("sec-fetch-site", "same-origin")
                .add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0")
                .build();

        requestBuilder.headers(headers);

        // 构建最终请求
        Request request = requestBuilder.build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            // 处理响应体
            System.out.println(Base64.getEncoder().encodeToString(response.body().bytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 字符解析成键值对参数
     * @return
     */
    public static Map<String, String> parseQueryParams (String path) {
        Map<String, String> map = new HashMap<>();
        if (StringUtils.isNotBlank(path)) {
            Matcher matcher = PAT_KEY_VALUE.matcher(path);
            while (matcher.find()) {
                String group = matcher.group(0);
                String[] split = group.split("=");
                if (split.length > 1) {
                    map.put(split[0], split[1]);
                } else {
                    map.put(split[0], "");
                }
            }
        }

        return map;
    }

}
